import { Select } from 'antd';
import React from 'react';
import {Raw} from '../types';

//透传Select的属性

type SelectProps = React.ComponentProps<typeof Select>;

interface IdSelectProps extends Omit<SelectProps,'value'|'onChange'|'options'>{
    value?: Raw|null|undefined,
    onChange?:(value?:number)=>void,
    defaultOptionsName?:string,
    options?:{name:string,id:number}[]
}

/**
 * value 可以传入多种类型的值
 * onChange只会回调number|undefined类型
 * 当isNaN(Number(value))为true的时候，代表选择默认类型
 * 当选择默认类型时，onChange返回undefined
 * @param props 
 * @returns 
 */

export const IdSelect = (props:IdSelectProps)=>{
    const {value,onChange,defaultOptionsName,options}  = props;

    return <Select 
            value={options?.length ? toNumber(value) : 0} 
            onChange={value=>onChange?.(toNumber(value)||undefined)}
            >
                {
                    defaultOptionsName ? <Select.Option value={0}>{defaultOptionsName}</Select.Option>:null
                }
                {
                    options?.map(option=><Select.Option key={option.id} value={option.id}>{option.name}</Select.Option>)   
                }
    </Select>
} 

const toNumber = (value:unknown)=>isNaN(Number(value)) ? 0 : Number(value);